﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.POIFS.Crypt.Dsig;
using System.Security.Claims;
using System.Text.RegularExpressions;

namespace DFGK_WMS.WebAPI.Controllers.基础数据
{
    /// <summary>
    /// 托盘管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PalletController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        public IPalletRepository PalletService { get; set; }
        public PalletController(IPalletRepository palletservice, ILogRepository logRepository)
        {
            PalletService = palletservice;
            this.logRepository = logRepository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPallet(PalletDto dto)
        {
            if (string.IsNullOrEmpty(dto.PalletBarcode))
            {
                return Ok(BaseResult.Result("400", "编码不能为空！"));
            }
            bool isko = PalletService.AddPallet(dto);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了托盘" + dto.PalletName;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败", "500"));
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdatePallet(PalletDto dto)
        {
            if(dto.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(dto.PalletBarcode))
            {
                return Ok(BaseResult.Result("400", "编码不能为空！"));
            }
            bool isko = PalletService.UpdatePallet(dto);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了托盘" + dto.PalletName;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelPallet(int ids)
        {
            if (ids <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool isko = PalletService.DelPallet(ids);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 5;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = rid;
                logg.Description = uname + "删除了托盘";
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败", "500"));
        }
        /// <summary>
        /// 托盘分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetPallets(string? name, int type = -1, int pageIndex = 1, int pageSize = 5)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount = 0;
            var list = PalletService.GetPallets(name, type, pageIndex, pageSize, out totalCount);
            if(list!=null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetPallet(int ids)
        {
            if (ids <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = PalletService.GetPallet(ids);
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// 获取枚举托盘类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmStationType()
        {
            var list = BaseEnum.GetCodeRulesList<PalletTypeEnum>();

            return Ok(list);
        }

        /// <summary>
        /// 查询出每个类型最大的对象
        /// </summary>
        /// <param name="PalletTypeId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTypePallet(int PalletTypeId)
        {
            var res = PalletService.GetTypePallet(PalletTypeId).OrderByDescending(p=>p.PalletBarcode).FirstOrDefault();
            return Ok(res);
        }

        #region 批量添加托盘弃用
        ///// <summary>
        ///// 批量添加托盘
        ///// </summary>
        ///// <param name="batchPalletDTO"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public IActionResult BatchPalletForm(BatchPalletDTO batchPalletDTO)
        //{
        //    List<TPallet> list = new List<TPallet>();
        //    string pattern = @"(\d+)$"; // 匹配最后的数字部分
        //    Match match = Regex.Match(batchPalletDTO.BeginBarcode, pattern);
        //    if (match.Success)
        //    {
        //        string numberString = match.Groups[1].Value; // 获取匹配到的数字部分
        //        long number = long.Parse(numberString); // 转换为整数
        //        for (int i = 0; i < batchPalletDTO.Num; i++)
        //        {
        //            number++; // 加一操作
        //            string incrementedNumberString = number.ToString();
        //            string resultString = Regex.Replace(batchPalletDTO.BeginBarcode, pattern, incrementedNumberString);
        //            list.Add(new TPallet()
        //            {
        //                PalletBarcode = resultString,
        //                Type = batchPalletDTO.Type,
        //                PalletName = (PalletTypeEnum)batchPalletDTO.Type + "-" + incrementedNumberString,
        //                Opprint = batchPalletDTO.IsPrint,
        //                Status = 1,
        //            });
        //        }
        //        if (PalletService.BatchAddPallet(list))
        //        {
        //            return Ok(BaseResult.Result(true,"批量添加成功！",list.Count()));
        //        }

        //    }
        //    return Ok(BaseResult.Result(null, "批量添加失败！", "500"));
        //}
        #endregion

        /// <summary>
        /// 批量添加托盘
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BatchPalletForm(BatchPalletDTO m)
        {
            if(m.Num<=0 || string.IsNullOrEmpty(m.BeginBarcode))
            {
                return Ok(BaseResult.Result("400", "参数有误！"));
            }
            bool result= PalletService.AddPalletList(m);
            if(result)
            {
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败", "500"));
        }
    }
}
